package com.example.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cron.CronExpression;
import com.example.mapper.SysJobInfoMapper;
import com.example.model.SysJobInfo;
import com.exmaple.dto.RpcRequest;
import com.exmaple.loadBalance.LoadBalanceEnum;
import com.exmaple.utils.IpUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SysJobInfoServiceImpl extends ServiceImpl<SysJobInfoMapper, SysJobInfo> implements SysJobInfoService {

    @Value("${server.port}")
    private int port;

    @Override
    public void refreshRunTime(Integer jobId, Long runTime) throws Exception {
        SysJobInfo sysJobInfo = getById(jobId);
        Date nextValidTime = this.generateNextValidTime(sysJobInfo, new Date(runTime));
        getBaseMapper().refreshRunTime(jobId, nextValidTime.getTime());
    }

    @Override
    public Date generateNextValidTime(SysJobInfo sysJobInfo, Date fromTime) throws Exception {
        return new CronExpression(sysJobInfo.getJobCron()).getNextValidTimeAfter(fromTime);
    }

    @Override
    public RpcRequest buildRequest(Integer jobId) {
        SysJobInfo sysJobInfo = getById(jobId);
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setFromId(IpUtil.getIp() + IpUtil.PREF + port);
        rpcRequest.setJobId(jobId);
        rpcRequest.setStartTime(System.currentTimeMillis());
        rpcRequest.setClassName(sysJobInfo.getJobClassName());
        rpcRequest.setLoadBalanceEnum(LoadBalanceEnum.RANDOM);
        return rpcRequest;
    }

    @Override
    public List<SysJobInfo> findListByTime(Long nextTime) {
        return getBaseMapper().findListByTime(nextTime);
    }
}
